var AREA_NEW = {
    AREA_NORMAL: 0,//正常区服
    AREA_NEW: 1,//新区
}

var oTable = $('#sample_editable_1').dataTable({
    "bProcessing": true,
    "aLengthMenu": [
        [5, 15, 20, -1],
        [5, 15, 20, "All"] // change per page values here
    ],
    // set the initial value
    "aaSorting": [[0, "desc"]],
    "iDisplayLength": 5,
    "sDom": "<'row-fluid'<'span6'l><'span6'f>r>t<'row-fluid'<'span6'i><'span6'p>>",
    "sPaginationType": "bootstrap",
    "oLanguage": {
        "sProcessing": "正在获取数据，请稍后...",
        "sLengthMenu": "每页显示_MENU_条记录",
        "sInfo": "从 _START_ 到 _END_ /共 _TOTAL_ 条数据",
        "oPaginate": {
            "sPrevious": "前一页",
            "sNext": "后一页",
        },
        "sZeroRecords": "抱歉， 没有找到",
        "sInfoEmpty": "没有数据"
    },

    "aoColumnDefs": [{
        'bSortable': false,
        'aTargets': [0]
    }
    ]
});
var TableEditable = function () {

    return {

        //main function to initiate the module
        init: function () {

            function restoreRow(oTable, nRow) {
                var aData = oTable.fnGetData(nRow);
                var jqTds = $('>td', nRow);

                for (var i = 0, iLen = jqTds.length; i < iLen; i++) {
                    oTable.fnUpdate(aData[i], nRow, i, false);
                }
                oTable.fnUpdate('<a class="edit" href="">编辑</a>', nRow, 7, false);
                oTable.fnUpdate('<a class="delete" href="">删除</a>', nRow, 8, false);

                oTable.fnDraw();
            }

            function editRow(oTable, nRow) {
                var aData = oTable.fnGetData(nRow);
                var jqTds = $('>td', nRow);
                jqTds[1].innerHTML = '<input type="text" class="m-wrap small" value="' + aData[1] + '">';
                jqTds[2].innerHTML = '<input type="text" class="m-wrap small" value="' + aData[2] + '">';
                jqTds[3].innerHTML = '<input type="text" class="m-wrap small" value="' + aData[3] + '">';
                jqTds[4].innerHTML = '<input type="text" class="m-wrap small" value="' + aData[4] + '">';
                jqTds[5].innerHTML = '<input type="text" class="m-wrap small" value="' + aData[5] + '">';
                var idstr = "#idnewServer" + aData[0];
                var htmlstr = "idnewServer" + aData[0];
                if ($(idstr).is(':checked') == true) {
                    jqTds[6].innerHTML = '<input id="' + htmlstr + '" type="checkbox" class="checkboxes" checked="checked" value=1>';
                } else {
                    jqTds[6].innerHTML = '<input id="' + htmlstr + '" type="checkbox" class="checkboxes" value=1>';
                }
                jqTds[7].innerHTML = '<a class="edit" href="">保存</a>';
                jqTds[8].innerHTML = '<a class="cancel" href="">取消</a>';
            }

            function GetNewId(oTable) {
                var nTrs = oTable.fnGetNodes();
                var tmax = 0;
                for (var i = 0; i < nTrs.length; i++) {
                    var t = oTable.fnGetData(nTrs[i])
                    if (t[0] > tmax) {
                        tmax = t[0];
                    }

                }
                return parseInt(tmax) + 1;
            }

            function saveRow(oTable, nRow) {
                var jqInputs = $('input', nRow);
                var bIpSucc = check_IP(jqInputs[1].value);
                var bipRepeat = check_IPRepeat(jqInputs[1].value);
                var bport = check_port(jqInputs[2].value);
                if (bIpSucc && bipRepeat && bport) {
                    oTable.fnUpdate(jqInputs[0].value, nRow, 1, false);
                    oTable.fnUpdate(jqInputs[1].value, nRow, 2, false);
                    oTable.fnUpdate(jqInputs[2].value, nRow, 3, false);
                    oTable.fnUpdate(jqInputs[3].value, nRow, 4, false);
                    oTable.fnUpdate(jqInputs[4].value, nRow, 5, false);
                    var aData = oTable.fnGetData(nRow);
                    var idstr = "#idnewServer" + aData[0];
                    var htmlstr = "idnewServer" + aData[0];
                    if ($(idstr).is(':checked') == true) {
                        oTable.fnUpdate('<input id="' + htmlstr + '" type="checkbox" class="checkboxes" checked="checked" value=1 disabled="disabled">', nRow, 6, false);
                    } else {
                        oTable.fnUpdate('<input id="' + htmlstr + '" type="checkbox" class="checkboxes" value=1 disabled="disabled">', nRow, 6, false);
                    }

                    oTable.fnUpdate('<a class="edit" href="">编辑</a>', nRow, 7, false);
                    oTable.fnUpdate('<a class="delete" href="">删除</a>', nRow, 8, false);
                    oTable.fnDraw();
                }

                return (bIpSucc && bipRepeat && bport);

            }

            function cancelEditRow(oTable, nRow) {
                var jqInputs = $('input', nRow);
                oTable.fnUpdate(jqInputs[0].value, nRow, 1, false);
                oTable.fnUpdate(jqInputs[1].value, nRow, 2, false);
                oTable.fnUpdate(jqInputs[2].value, nRow, 3, false);
                oTable.fnUpdate(jqInputs[3].value, nRow, 4, false);
                oTable.fnUpdate(jqInputs[4].value, nRow, 5, false);
                oTable.fnUpdate('<a class="edit" href="">编辑</a>', nRow, 6, false);
                oTable.fnDraw();
            }

            jQuery('#sample_editable_1_wrapper .dataTables_filter input').addClass("m-wrap medium"); // modify table search input
            jQuery('#sample_editable_1_wrapper .dataTables_length select').addClass("m-wrap small"); // modify table per page dropdown
            jQuery('#sample_editable_1_wrapper .dataTables_length select').select2({
                showSearchInput: false //hide search box with special css class
            }); // initialzie select2 dropdown


            var nEditing = null;//记录编辑第几行

            $('#sample_editable_1_new').click(function (e) {
                e.preventDefault();
                var newId = GetNewId(oTable)
                var aiNew = oTable.fnAddData([newId, '', '', '', '', '', '',
                    '<a class="edit" href="">编辑</a>', '<a class="cancel" data-mode="new" href="">取消</a>'
                ]);

                var nRow = oTable.fnGetNodes(aiNew[0]);
                editRow(oTable, nRow);
                nEditing = nRow;
            });

            $('#sample_editable_1 a.delete').live('click', function (e) {
                e.preventDefault();

                if (confirm("确定删除此行 ?") == false) {
                    return;
                }

                var nRow = $(this).parents('tr')[0];

                //alert("Deleted! Do not forget to do some ajax to sync with backend :)");
                var DelData = oTable.fnGetData(nRow);
                var cs2DelData = {
                    "name": DelData[1],
                    "ip": DelData[2],
                    "port": DelData[3],
                    "area": DelData[4],
                    "chan_id": DelData[5],
                    "newServer": (function () {
                        var val = AREA_NEW.AREA_NORMAL;
                        var idstr = "#idnewServer" + DelData[0];
                        if ($(idstr).is(':checked') == true) {
                            val = AREA_NEW.AREA_NEW;
                        }
                        return val;
                    })(),
                };
                $.post("/c2sDel", cs2DelData)
                    .success(function () {
                            oTable.fnDeleteRow(nRow);
                            alert("删除数据库成功");
                        }
                    );
            });

            $('#sample_editable_1 a.cancel').live('click', function (e) {
                e.preventDefault();
                var nRow = $(this).parents('tr')[0];
                var bEmpty = checkAllRowEmpty(nRow);

                if (($(this).attr("data-mode") == "new") || bEmpty) {
                    oTable.fnDeleteRow(nRow);
                } else {
                    restoreRow(oTable, nEditing);
                    nEditing = null;
                }
            });

            $('#sample_editable_1 a.edit').live('click', function (e) {
                e.preventDefault();

                /* Get the row as a parent of the link that was clicked on */
                var nRow = $(this).parents('tr')[0];

                if (nEditing !== null && nEditing != nRow) {
                    /* Currently editing - but not this row - restore the old before continuing to edit mode */
                    restoreRow(oTable, nEditing);
                    editRow(oTable, nRow);
                    nEditing = nRow;
                } else if (nEditing == nRow && this.innerHTML == "保存") {
                    /* Editing this row and want to save it */
                    var bipAuth = saveRow(oTable, nEditing);
                    if (bipAuth) {
                        nEditing = null;
                        //alert("Updated! Do not forget to do some ajax to sync with backend :)");
                        var cs2Data = oTable.fnGetData(nRow);
                        var c2sSaveData = {
                            "name": cs2Data[1],
                            "ip": cs2Data[2],
                            "port": cs2Data[3],
                            "area": cs2Data[4],
                            "chan_id": cs2Data[5],
                            "newServer": (function () {
                                var val = AREA_NEW.AREA_NORMAL;
                                var idstr = "#idnewServer" + cs2Data[0];
                                if ($(idstr).is(':checked') == true) {
                                    val = AREA_NEW.AREA_NEW;
                                }
                                return val;
                            })(),
                        };

                        $.post("/c2sSave", c2sSaveData)
                            .success(function () {
                                alert("更新数据库成功");
                            });
                    }

                } else {
                    /* No edit in progress - let's start one */
                    editRow(oTable, nRow);
                    nEditing = nRow;
                }
            });


            function check_IPRepeat(ip) {
                var nTrs = oTable.fnGetNodes();
                for (var i = 0; i < nTrs.length; i++) {
                    var t = oTable.fnGetData(nTrs[i])
                    if ((t[0] == ip) && (nEditing != nTrs[i])) {
                        alert("IP重复，重复ip：" + t[0]);
                        return false;
                    }

                }
                return true;
            }

            //检查是不是全部列都是空的行
            function checkAllRowEmpty(nRow) {
                var aData = oTable.fnGetData(nRow);
                if ((aData[1] == "") && (aData[2] == "")
				   && (aData[3] == "")&& (aData[4] == "")&& (aData[5] == "")) {
                    return true
                }
                return false
            }

        }

    };

}();

function getAllData() {
    //数据量不是特别大，直接全部读取吧
    $.getJSON("/admingetServerData", function (data, status) {
        if (status == "success") {
            console.log(data);
            $.each(data, function (i, item) {
                var aiNew = oTable.fnAddData([i + 1, item.name, item.ip, item.port, item.area, item.chan_id, '<input type="checkbox" class="m-wrap small">',
                    '<a class="edit" href="">编辑</a>', '<a class="cancel" data-mode="new" href="">删除</a>'
                ]);

                var nRow = oTable.fnGetNodes(aiNew[0]);
                oTable.fnUpdate(i + 1, nRow, 0, false);
                oTable.fnUpdate(item.name, nRow, 1, false);
                oTable.fnUpdate(item.ip, nRow, 2, false);
                oTable.fnUpdate(item.port, nRow, 3, false);
                oTable.fnUpdate(item.area, nRow, 4, false);
                oTable.fnUpdate(item.chan_id, nRow, 5, false);
                var htmlstr = "idnewServer" + i + 1;
                if (item.newServer == AREA_NEW.AREA_NEW) {
                    var htmlstr = '<input id="' + htmlstr + '"type="checkbox" class="checkboxes" checked="checked" disabled="disabled">';
                    oTable.fnUpdate(htmlstr, nRow, 6, false);
                } else {
                    var htmlstr = '<input id="' + htmlstr + '"type="checkbox" class="checkboxes" disabled="disabled">';
                    oTable.fnUpdate(htmlstr, nRow, 6, false);
                }
                oTable.fnUpdate('<a class="edit" href="">编辑</a>', nRow, 7, false);
                oTable.fnUpdate('<a class="delete" href="">删除</a>', nRow, 8, false);

            });
            oTable.fnDraw();

        }
    });
}

function check_IP(ip) {
    var re = /^(\d+)\.(\d+)\.(\d+)\.(\d+)$/;//正则表达式
    if (re.test(ip)) {
        if (RegExp.$1 < 256 && RegExp.$2 < 256 && RegExp.$3 < 256 && RegExp.$4 < 256)
            return true;
    }
    alert("IP格式有误！");
    return false;
}

function check_port(port) {
    var re = /^[0-9]*[1-9][0-9]*$/;   //判断字符串是否为数字
    if (re.test(port)) {
        return true;
    }
    alert("端口只能输入数字！");
    return false;
}

